/**
 * @author xiao zhou
 * @lastEditTime 2021-06-09 16:19:14
 * @description
 */

const program = require('commander')
const chalk = require('chalk')
const leven = require('leven')
const { packageInfo } = require('./config')
const { log } = require('./utils')

module.exports = argv => {
  // 设置默认命令
  program
    .version(packageInfo.version, '-v, --version', '输出当前版本号')
    .usage('<command> [options] 快速启动项目') // -h 打印的用户提示
    .helpOption('-h, --help', '获取帮助')
    .addHelpCommand(false)

  // 注册命令
  program
    .command('init')
    .description('初始化自动部署项目')
    .alias('i')
    .action(() => {
      require('./commands/init')()
    })

  program
    .command('deploy')
    .description('前端自动化部署项目')
    .alias('d')
    .option('-m, --mode <mode>', '设置自动部署环境')
    .option('--no-build', '跳过本地打包过程')
    .action(options => {
      require('./commands/deploy')(options)
    })

  // 输出未知命令的帮助信息
  program.on('command:*', ([unknownCommand]) => {
    program.outputHelp()
    log('  ' + chalk.red(`Unknown command ${chalk.yellow(unknownCommand)}.`))
    log()
    // eslint-disable-next-line no-undef
    const availableCommands = program.commands.map(cmd => cmd._name)
    let suggestion
    availableCommands.forEach(cmd => {
      const isBestMatch = leven(cmd, unknownCommand) < leven(suggestion || '', unknownCommand)
      if (leven(cmd, unknownCommand) < 3 && isBestMatch) {
        suggestion = cmd
      }
    })
    if (suggestion) {
      log(`   ${ chalk.red(`Did you mean ${chalk.yellow(suggestion)}?`)}`)
    }
  })

  // 添加一些有用的帮助信息
  program.on('--help', () => {
    log()
    log(`  Run ${chalk.cyan('@xz2xl/auto-deploy <command> --help')} for detailed usage of given command.`)
    log()
  })

  program.commands.forEach(c => c.on('--help', () => log()))

  program.parse(argv)
}
